import json

from django.views.decorators.http import require_POST, require_GET

from common.base_view import BaseView, response_json
from common.const import CODE_OK, CODE_SYSTEM_ERROR, CODE_TOKEN_EXPIRE, CODE_NOT_LOGIN, CODE_USER_EXIST, \
    CODE_USER_NOT_EXIST, CODE_USER_OLD_PASS_ERROR
from common.jwt_utils import authenticated, JWT, authenticated_super
from common.lib_mysql import News
from db_models.booms import Booms
from db_models.comment import Comment
from db_models.news_body import NewsBody
from db_models.users import User


class BoomView(BaseView):
    @authenticated_super
    def get(self, request):
        try:
            page = request.GET.get("page")
            search_key = request.GET.get("search_key")
            status = request.GET.get("status")
            return Booms().list(int(page), search_key, status)
        except Exception as e:
            print("BoomView get error", e)
            return response_json(CODE_SYSTEM_ERROR)

    @authenticated_super
    def delete(self, request):
        try:
            body = json.loads(request.body)
            ids = body.get("ids")
            return Booms().delete([str(i) for i in ids])
        except Exception as e:
            print("BoomView delete error", e)
            return response_json(CODE_SYSTEM_ERROR)

    @authenticated_super
    def put(self, request):
        try:
            body = json.loads(request.body)
            ids = body.get("ids")
            up_dict = {
                "status": int(body.get("status")),
                "title": body.get("title"),
            }
            return Booms().update([str(i) for i in ids], up_dict)
        except Exception as e:
            print("BoomView put error", e)
            return response_json(CODE_SYSTEM_ERROR)

    @authenticated_super
    def post(self, request):
        try:
            body = json.loads(request.body)
            insert_dict = {
                "status": int(body.get("status")),
                "title": body.get("title"),
                "url": body.get("url")
            }
            return Booms().insert(insert_dict)
        except Exception as e:
            print("BoomView post error", e)
            return response_json(CODE_SYSTEM_ERROR)


@require_GET
def boom_view(request):
    try:
        booms = News().exec_sql("select * from users_boom where status=2")
        return response_json(CODE_OK, booms)
    except Exception as e:
        print("boom_view error", e)
        return response_json(CODE_SYSTEM_ERROR)


@require_GET
def news_view(request):
    try:
        page = request.GET.get("page")
        search_key = request.GET.get("search_key")
        new_type = request.GET.get("new_type")
        if new_type == "全部":
            new_type = ""
        return NewsBody().list(int(page), search_key, new_type, -1)
    except Exception as e:
        print("news_view error", e)
        return response_json(CODE_SYSTEM_ERROR)


@require_POST
def pass_reset(request):
    try:
        body = json.loads(request.body)
        id= str(body.get("id"))
        old_pass = body.get("old_password")
        infos = User().find_one("select * from users_users where id = {}".format(id))
        if infos and len(infos):
            if infos.get("password") == old_pass:
                return User().update(id, {"password": str(body.get("password"))})
            else:
                return response_json(CODE_USER_OLD_PASS_ERROR)
        else:
            return response_json(CODE_USER_NOT_EXIST)
    except Exception as e:
        print("pass_reset error", e)
        return response_json(CODE_SYSTEM_ERROR)


@require_POST
def add_comment(request):
    try:
        body = json.loads(request.body)
        comment = body.get("comment")
        new_id = str(body.get("id"))
        token = request.headers.get("Authorization")
        infos = JWT.verify_jwt(token)
        if not token or not infos:
            return response_json(CODE_NOT_LOGIN)
        insert_dict = {
            "username": infos.get("username"),
            "new_id": new_id,
            "content": comment,
            "photo": infos.get("photo")
        }
        return Comment().insert(insert_dict)
    except Exception as e:
        print("add_comment error", e)
        return response_json(CODE_SYSTEM_ERROR)


@require_GET
def news_find_view(request):
    try:
        id = request.GET.get("id")
        return NewsBody().find_one_by_id(int(id))
    except Exception as e:
        print("news_find_view error", e)
        return response_json(CODE_SYSTEM_ERROR)


@require_POST
def login(request):
    body = json.loads(request.body)
    return User().user_login(body.get("phone"), body.get("password"))


@require_POST
def login_user(request):
    body = json.loads(request.body)
    return User().user_login1(body.get("phone"), body.get("password"))


@require_GET
def info(request):
    token = request.headers.get("Authorization")
    infos = JWT.verify_jwt(token)
    if not token or not infos:
        return response_json(CODE_TOKEN_EXPIRE)
    id = infos.get("id")
    infos = User().find_one("select * from users_users where id = {}".format(id))
    if infos and infos.get("password"):
        del infos["password"]
        return response_json(CODE_OK, infos)
    return response_json(CODE_SYSTEM_ERROR)


@require_GET
def userinfo(request):
    token = request.headers.get("Authorization")
    infos = JWT.verify_jwt(token)
    if not token or not infos:
        return response_json(CODE_NOT_LOGIN)
    id = infos.get("id")
    infos = User().find_one("select * from users_users where id = {}".format(id))
    if infos and infos.get("password"):
        del infos["password"]
        return response_json(CODE_OK, infos)
    return response_json(CODE_SYSTEM_ERROR)


class AdminUserManage(BaseView):
    @authenticated_super
    def get(self, request):
        try:
            page = request.GET.get("page")
            search_key = request.GET.get("search_key")
            return User().list(int(page), search_key)
        except Exception as e:
            print("AdminUserManage get error", e)
            return response_json(CODE_SYSTEM_ERROR)

    @authenticated
    def put(self, request):
        try:
            body = json.loads(request.body)
            up_dict = {
                "photo": body.get("photo"),
                "gender": str(body.get("gender")),
                "email": str(body.get("email")),
                "city": body.get("city"),
                "address": body.get("address"),
                "region": body.get("region"),
                "username": body.get("username"),
                "nickname": body.get("nickname"),
            }
            id = body.get("id")
            return User().update(str(id), up_dict)
        except Exception as e:
            print("AdminUserManage put error", e)
            return response_json(CODE_SYSTEM_ERROR)

    @authenticated
    def post(self, request):
        try:
            body = json.loads(request.body)
            phone = body.get("phone")
            res = User().find_one("select * from users_users where phone = {}".format(phone))
            if res and len(res):
                return response_json(CODE_USER_EXIST)
            insert_dict = {
                "photo": body.get("photo"),
                "gender": str(body.get("gender")),
                "email": str(body.get("email")),
                "city": body.get("city"),
                "address": body.get("address"),
                "region": body.get("region"),
                "username": body.get("username"),
                "nickname": body.get("nickname"),
                "phone": body.get("phone"),
                "country": "中国",
                "password": body.get("password"),
                "user_type": 2,
                "age": 18
            }
            return User().insert(insert_dict)
        except Exception as e:
            print("AdminUserManage post error", e)
            return response_json(CODE_SYSTEM_ERROR)

    @authenticated
    def delete(self, request):
        try:
            body = json.loads(request.body)
            ids = body.get("ids")
            return User().delete([str(i) for i in ids])
        except Exception as e:
            print("AdminUserManage delete error", e)
            return response_json(CODE_SYSTEM_ERROR)


class AdminNewsManage(BaseView):
    @authenticated
    def get(self, request):
        try:
            token = request.headers.get("Authorization")
            infos = JWT.verify_jwt(token)
            if not token or not infos:
                return response_json(CODE_NOT_LOGIN)
            user_id = -1
            if infos.get("user_type") == 2:
                user_id = infos.get("id")
            page = request.GET.get("page")
            search_key = request.GET.get("search_key")
            new_type = request.GET.get("new_type")
            return NewsBody().list(int(page), search_key, new_type, user_id)
        except Exception as e:
            print("AdminNewsManage get error", e)
            return response_json(CODE_SYSTEM_ERROR)

    @authenticated
    def delete(self, request):
        try:
            body = json.loads(request.body)
            ids = body.get("ids")
            return NewsBody().delete([str(i) for i in ids])
        except Exception as e:
            print("AdminNewsManage delete error", e)
            return response_json(CODE_SYSTEM_ERROR)

    @authenticated
    def put(self, request):
        try:
            body = json.loads(request.body)
            id = body.get("id")
            up_dict = {
                "new_type": body.get("new_type"),
                "content": str(body.get("content")),
                "body": str(body.get("body")),
                "url": str(body.get("url")),
                "title": body.get("title"),
                "image_url": body.get("image_url")
            }
            return NewsBody().update(str(id), up_dict)
        except Exception as e:
            print("AdminNewsManage put error", e)
            return response_json(CODE_SYSTEM_ERROR)

    @authenticated
    def post(self, request):
        try:
            token = request.headers.get("Authorization")
            infos = JWT.verify_jwt(token)
            if not token or not infos:
                return response_json(CODE_NOT_LOGIN)
            body = json.loads(request.body)
            insert_dict = {
                "new_type": body.get("new_type"),
                "content": str(body.get("content")),
                "url": str(body.get("url")),
                "body": str(body.get("body")),
                "title": body.get("title"),
                "image_url": body.get("image_url"),
                "user_id": infos.get("id"),
                "username": infos.get("username")
            }
            return NewsBody().insert(insert_dict)
        except Exception as e:
            print("AdminNewsManage post error", e)
            return response_json(CODE_SYSTEM_ERROR)


class AdminCommentsManage(BaseView):
    # @authenticated 不需要鉴权也可访问
    def get(self, request):
        try:
            page = request.GET.get("page")
            id = request.GET.get("id")
            return Comment().list(int(page), id)
        except Exception as e:
            print("AdminCommentsManage get error", e)
            return response_json(CODE_SYSTEM_ERROR)

    @authenticated
    def delete(self, request):
        try:
            body = json.loads(request.body)
            id = body.get("id")
            return Comment().delete([str(id)])
        except Exception as e:
            print("AdminCommentsManage delete error", e)
            return response_json(CODE_SYSTEM_ERROR)
